/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.code.motoo.ssl;

import com.google.code.motoo.core.IoBuffer;
import com.google.code.motoo.core.IoSession;
import com.google.code.motoo.filter.IoFilter;

/**
 * 实现了SSL加密和解密的过滤器，每一个IoSession有自己的一个SSLHandler
 * @author linfengqi
 * @version 1.0
 * @date May 4, 2009
 */
public class SSLFilter implements IoFilter{
	
	private SSLHandlerFactory sSLHandlerFactory;
	private final static String SSL_HANDLER_TAG = "ssl_handler";
	
	public SSLFilter(SSLHandlerFactory factory) {
		this.sSLHandlerFactory = factory;
	}
	
	public void messageReceived(NextIoFilter nextFilter, IoSession session, Object message) throws Exception {
		SSLHandler sSLHandler = getSSLHandlerFromSession(session);
		
		IoBuffer buffer = (IoBuffer) message;
		sSLHandler.messageReceived(nextFilter, buffer.buf());
		IoBuffer appBuffer = sSLHandler.fetchAppBuffer();
		if (appBuffer != null && appBuffer.hasRemaining())
			nextFilter.messageReceived(session, appBuffer);
		
		buffer.clear();
	}

	public void messageSend(NextIoFilter nextFilter, IoSession session, Object message) throws Exception {
		SSLHandler sSLHandler = getSSLHandlerFromSession(session);
		IoBuffer buffer = (IoBuffer) message;
		sSLHandler.encrypt(buffer.buf());
		IoBuffer outNetBuffer = sSLHandler.fetchOutNetBuffer();
		nextFilter.messageSend(session, outNetBuffer);
		
	}
	
	private SSLHandler getSSLHandlerFromSession(IoSession session) throws Exception {
		SSLHandler sSLHandler = null;
		if (session.containsAttribute(SSL_HANDLER_TAG)) {
			sSLHandler = (SSLHandler) session.getAttribute(SSL_HANDLER_TAG);
		} else {
			sSLHandler = sSLHandlerFactory.createSSLHandler(session);
			session.setAttribute(SSL_HANDLER_TAG, sSLHandler);
		}
		
		return sSLHandler;
	}

	public void destroy() throws Exception {
		// TODO Auto-generated method stub
		
	}

	public void init() throws Exception {
		// TODO Auto-generated method stub
		
	}

}
